package com.etl.sys.service.impl;

import com.etl.enums.ScheduleStatusEnum;
import com.etl.sys.entity.SysSchedule;
import com.etl.sys.mapper.SysScheduleMapper;
import com.etl.sys.service.ISysScheduleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etl.task.basic.TaskResult;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 调度表 服务实现类
 * </p>
 *
 * @author chenfenghai
 * @since 2020-10-26
 */
@Service
public class SysScheduleServiceImpl extends ServiceImpl<SysScheduleMapper, SysSchedule> implements ISysScheduleService {

    /**
     * 更新调度状态
     *
     * @param scheduleId     调度ID
     * @param scheduleStatus 状态
     */
    @Override
    public void updateScheduleStatus(Long scheduleId, ScheduleStatusEnum scheduleStatus) {
        LocalDateTime now = LocalDateTime.now();
        SysSchedule sysSchedule = new SysSchedule();
        sysSchedule.setScheduleId(scheduleId);
        sysSchedule.setUpdateTime(now);
        sysSchedule.setRunStatus(scheduleStatus.getCode());
        super.updateById(sysSchedule);
    }

    /**
     * 更新调度结果
     *
     * @param scheduleId 调度ID
     * @param taskResult 结果
     */
    @Override
    public void updateScheduleResult(Long scheduleId, TaskResult taskResult) {
        LocalDateTime now = LocalDateTime.now();
        SysSchedule sysSchedule = new SysSchedule();
        sysSchedule.setScheduleId(scheduleId);
        sysSchedule.setUpdateTime(now);
        if (Objects.nonNull(taskResult) && taskResult.isSuccess()) {
            sysSchedule.setLastSign(taskResult.getLastSign());
            sysSchedule.setLastSuccessTime(now);
        } else {
            sysSchedule.setLastFailureTime(now);
        }
        super.updateById(sysSchedule);
    }

    /**
     * 更新调度为已停止、已失败
     *
     * @param scheduleId 调度ID
     */
    @Override
    public void updateScheduleToStoppedAndFailed(Long scheduleId){
        LocalDateTime now = LocalDateTime.now();
        SysSchedule sysSchedule = new SysSchedule();
        sysSchedule.setUpdateTime(now);
        sysSchedule.setLastFailureTime(now);
        sysSchedule.setRunStatus(ScheduleStatusEnum.STOPPED.getCode());
        super.updateById(sysSchedule);
    }
}
